package dao

import (
	"week33/inits"
	"week33/model"
)

func Login(tel string, password string) (result *model.User) {
	err := inits.DB.Where("tel=?", tel).Where("password=?", password).Find(&result).Error
	if err != nil {
		return nil
	}
	return result
}

func Register(tel string, password string) (result *model.User) {
	result = &model.User{
		Tel:      tel,
		Password: password,
	}
	err := inits.DB.Create(&result).Error
	if err != nil {
		return nil
	}
	return result
}

func AddArticle(userId int, articleType int, num int, context string) (result *model.Article) {
	result = &model.Article{
		Context:     context,
		UserId:      userId,
		ArticleType: articleType,
		LikeNum:     num,
	}
	err := inits.DB.Create(&result).Error
	if err != nil {
		return nil
	}
	return result
}

func List(userId int) []model.Article {
	var result []model.Article
	err := inits.DB.Raw("SELECT * FROM article e LEFT JOIN (SELECT focus_id FROM focus WHERE user_id=?) a ON e.user_id=a.focus_id ORDER BY focus_id DESC,like_num DESC", userId).Scan(&result).Error
	if err != nil {
		return []model.Article{}
	}
	return result
}

func Focus(userId int, focusId int) (result *model.Focus) {
	result = &model.Focus{
		UserId:  userId,
		FocusId: focusId,
	}
	err := inits.DB.Create(&result).Error
	if err != nil {
		return nil
	}
	return result
}

func AddRoom(userId int, roomId int) bool {
	result1 := model.Room{
		RoomUserId: userId,
	}
	err := inits.DB.Create(&result1).Error
	if err != nil {
		return false
	}
	result2 := model.RoomUser{
		RoomId:     roomId,
		RoomUserId: userId,
		ULevel:     1,
	}
	err = inits.DB.Create(&result2).Error
	if err != nil {
		return false
	}

	return true
}

func AddRoomUser(userId int, roomId int, level int) bool {
	result := model.RoomUser{
		RoomId:     roomId,
		RoomUserId: userId,
		ULevel:     level,
	}
	err := inits.DB.Create(&result).Error
	if err != nil {
		return false
	}

	return true
}

func UpdateLevel(userId int, level int, roomId int) bool {
	err := inits.DB.Model(&model.RoomUser{}).Where("room_id", roomId).Where("room_user_id", userId).Update("u_level", level).Error
	if err != nil {
		return false
	}
	return true
}

func DelRoom(userId int) bool {
	err := inits.DB.Where("room_user_id", userId).Delete(&model.Room{}).Error
	if err != nil {
		return false
	}
	return true
}
